<?php
namespace App\Support;
use App\Support\Redis;

class Data {
	private $path, $prefix, $redis;

	function __construct(Redis $redis) {
		$this->path = storage_path('app/data');
		$this->redis = $redis;
		$this->prefix = config('app.name') . ':info:';
	}

	public function getResume() {
		return $this->getCache('resume');
	}

	public function getInfo() {
		return $this->getCache('info');
	}

	public function setResume($string) {
		return $this->setCache($string, 'resume');
	}

	public function setInfo($string) {
		return $this->setCache($string, 'info');
	}

	private function setCache($string, $type) {
		$cache_key = $this->prefix . $type;
		$file_name = $this->path . DIRECTORY_SEPARATOR . $type . '.md';
		if (file_exists($file_name)) {
			rename($file_name, $file_name . '_bak' . date('Y-m-d'));
		}
		if ($this->redis->exists($cache_key)) {
			$this->redis->del($cache_key);
		}
		if ($string != '') {
			file_put_contents($file_name, $string);
		}
		return true;
	}

	private function getCache($type) {
		$cache_key = $this->prefix . $type;
		$string = '';
		if (!$this->redis->exists($cache_key)) {
			$file_name = $this->path . DIRECTORY_SEPARATOR . $type . '.md';
			if (file_exists($file_name)) {
				$string = file_get_contents($file_name);
				$this->redis->set($cache_key, $string);
			} else {
				return '';
			}
		}
		return $string != '' ? $string : $this->redis->get($cache_key);
	}
}